package cn.com.cifi.mars.web.action;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import cn.com.cifi.mars.bean.vo.sys.req.DemoReqParam;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.common.redis.RedisTemplateUtil;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.service.CacheService;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.util.JwtUtil;

@RestController
public class DemoAction extends BaseAction implements IDemo {

	@Autowired
	private RedisTemplateUtil redisTemplateUtil;

	@Autowired
	private IdmUserService idmUserService;

	@Autowired
	private CacheService cacheService;

	@Value("${api_admin_password}")
	private String adminPassword;

	@Override
	public R<String> currentUser(String apiVersion) {
		IdmUser user = getOperator();
		if(user == null) {
			throw new MsgException(CodeEnum.NOT_NONE_PERMISSION);
		}
		return ok(user);
	}

	@Override
	public R<String> loginTmp(String apiVersion, String userId, String password) {
		if (!password.equals(adminPassword)) {
			throw new MsgException(CodeEnum.ERROR_PASSWORD);
		}
		String sessionToken = JwtUtil.createToken(userId);
		IdmUser user = idmUserService.selectByUserName(userId);
		redisTemplateUtil.set("mars_user_" + sessionToken, user, 8, TimeUnit.HOURS);
		return ok(sessionToken);
	}

	/**
	 * 测试redis
	 */
	@Override
	public R<String> getRedis(String apiVersion, String value) {
		return ok(value);
	}

	public R refreshCache(String apiVersion, String key) {
		if (StringUtils.isBlank(key)) {
			return fail("key 不能为空");
		}
		cacheService.removeKey(key);
		return ok();
	}

}
